package com.jaychen.eureka.exception;

import com.jaychen.eureka.enumeration.ServerExceptionCodeEnum;
import com.jaychen.eureka.result.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.List;

/**
 * 全局异常处理器
 *
 * @author longyuan
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 服务器异常
     *
     * @param e Exception
     * @return YogUserResult
     */
    @ExceptionHandler({Exception.class})
    public Result handleException(Exception e) {
        log.error(e.getMessage(), e);
        return Result.builder()
                .code(ServerExceptionCodeEnum.SERVER_ERROR.getCode())
                .msg(ServerExceptionCodeEnum.SERVER_ERROR.getMsg())
                .build();
    }

    /**
     * 参数异常
     *
     * @param e MethodArgumentNotValidException
     * @return YogUserResult
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public Result handleException(MethodArgumentNotValidException e) {
        log.error(e.getMessage(), e);
        List<FieldError> fieldError = e.getBindingResult().getFieldErrors();
        StringBuffer buffer = new StringBuffer();
        fieldError.forEach((field) -> {
            if (buffer.length() > 0) {
                buffer.append("-");
            }

            buffer.append(field.getDefaultMessage());
        });
        return Result.builder()
                .code(ServerExceptionCodeEnum.ILLEGAL_PARAM.getCode())
                .msg(buffer.toString())
                .build();
    }
}
